<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors',1);
$expected = array(
		'cmd'
	,	'api'
	,	'quickMode'
	,	'setAuthor'
	,	'setTaxa'
	,	'projectId'
	,	'stages'
	,	'sort'
	,	'start'
	,	'limit'
	,	'dir'
	,	'pAuth'
	,	'sAuth'
	,	'url'
	,	'classificationId'
	,	'exported'
	,	'field'
	,	'query'
	,	'searchType'
); 

// Initialize allowed variables
foreach ($expected as $formvar)
	$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? ${"_$_SERVER[REQUEST_METHOD]"}[$formvar]:NULL;

include_once('../../config.php');
include_once($config['paths']['base'] . 'resources/api/classes/class.classify.php');

$classify = new Classify();

$valid = true;
header('Content-type: application/json');
switch($cmd) {
	case 'classify':
		$pAuth = $pAuth;
		$sAuth = $sAuth;

		if($pAuth != '') {
			$rs = json_decode(@file_get_contents($config['GBIFAuthorityUrl'] . $pAuth));
			if($rs->success == true) {
				$pAuthText = $rs->data->title;
			}
		}
		if($sAuth != '') {
			$rs = json_decode(@file_get_contents($config['GBIFAuthorityUrl'] . $sAuth));
			if($rs->success == true) {
				$sAuthText = $rs->data->title;
			}
		}

		$quickMode = (trim($quickMode) == '1') ? 1 : 0;

		if(!$classify->project->projectExists($config['db']['name'],$projectId)) {
			print json_encode(array('success' => false, 'error' => array('code' => 110, 'msg' => $classify->getError(110))));
			break;
		}

		if(!$classify->project->loadByProjectId($projectId)){
			$valid = false;$code = 104;
		}

		if($pAuth == '' && $sAuth == '') {
			$valid = false;$code = 107;
		}

		if($valid) {
			if(!in_array($classify->project->get('stage'), array('LOADED','CLASSIFYING','CLASSIFIED','ARCHIVING','ARCHIVED'))) {
				$valid = false;
				$code = 105;
			} else {
				$classify->project->resetClassifyFlag($classify->project->get('projectId'));
				$classify->project->set('stage', 'CLASSIFYING');
				$classify->project->set('pAuth', $pAuth);
				$classify->project->set('pAuthText', $pAuthText);
				$classify->project->set('sAuth', $sAuth);
				$classify->project->set('sAuthText', $sAuthText);
				$classify->project->set('quickMode', $quickMode);
				$classify->project->set('setAuthor', $setAuthor);
				$classify->project->set('setTaxa', $setTaxa);
				if($classify->project->save()) {
					print json_encode(array('success' => true,'status' => 'CLASSIFYING'));
				}
			}
		} 
		if(!$valid) {
			print json_encode(array('success' => false, 'error' => array('errorCode' => $code, 'errorMessage' => $classify->getError($code))));
		}
		break;
	case 'archive':
		if(!$classify->project->projectExists($config['db']['name'], $projectId)) {
			print json_encode(array('success' => false, 'error' => array('code' => 110, 'msg' => $classify->getError(110))));
			break;
		}
		if(!$classify->project->loadByProjectId($projectId)){
			$valid = false;$code = 104;
		}
		If($valid) {
			if($classify->project->get('stage') != 'CLASSIFIED') {
				$valid = false;
				$code = 106;
			} else {
				$classify->project->set('stage', 'ARCHIVING');
				if($classify->project->save()) {
					print json_encode(array('success' => true,'status' => 'ARCHIVING'));
				}
			}
		} 
		if(!$valid) {
			print json_encode(array('success' => false, 'error' => array('errorCode' => $code, 'errorMessage' => $classify->getError($code))));
		}

		break;

	case 'getStatus':
		$projectId = trim($projectId);

		if($classify->project->loadByProjectId($projectId, true)) {
			if(!$classify->project->projectExists($config['db']['name'], $projectId) && $classify->project->get('stage') != 'ERROR') {
				$output = array('success' => true, 'status' => 'NEW');
				print json_encode($output);
				break;
			}

			switch($classify->project->get('stage')) {
				case 'ARCHIVED':
					$bool = $classify->project->getQuickMode();
					$output = array('success' => true, 'allowQuickmode' => $bool, 'status' => 'ARCHIVED',  'archiveUrl' => $config['projectUrl'] . $projectId . '/' . $projectId . '.zip');
					break;

				case 'ERROR':
					$output = array('success' => true, 'status' => 'ERROR',  'comments' => $classify->project->get('comments'));
					break;

				case 'CLASSIFYING':
					$bool = $classify->project->getQuickMode();
					$output = array('success' => true, 'allowQuickmode' => $bool, 'status' => 'CLASSIFYING',  'x' => $classify->project->get('x'), 'y' => $classify->project->get('y'), 'queuedProjects' => $classify->project->getQueuedProjectCount() );
					break;

				default:
					$bool = $classify->project->getQuickMode();
					$output = array('success' => true, 'allowQuickmode' => $bool, 'status' => $classify->project->get('stage'));
					break;
			}
			print json_encode($output);
		} else {
			print json_encode(array('success' => false, 'error' => array('code' => 104, 'msg' => $classify->getError(104))));
		}
		break;

	case 'listProjects':
		$timeStart = microtime(true);
		$stages = json_decode(stripslashes(trim($stages)), true);
		if(is_array($stages) && count($stages)) {
			$filter['filter'][] = array('data' => array('type' => 'list', 'value' => @implode(',',$stages)),'field' => 'stage');
		}
		$projects = $classify->project->getByFilter($filter);
		$projects = is_null($projects) ? array() : $projects;
		print json_encode(array('success' => true,'processTime' => (microtime(true) - $timeStart), 'records' => $projects));
		break;

	case 'addProject':
		$projectId = trim($projectId);
		$classify->project->loadByProjectId($projectId);
		(trim($url) != '') ? $classify->project->set('url', trim($url)) : '';
		$classify->project->set('ip', $_SERVER['REMOTE_ADDR']);
		(trim($classificationId) != '') ? $classify->project->set('classificationId', trim($classificationId)) : '';
		(trim($exported) != '') ? $classify->project->set('exported', trim($exported)) : '';
		$classify->project->save();
		$classify->project->loadById($classify->project->db->insert_id);
		print json_encode( array('success' => true, 'projectId' => $classify->project->get('projectId'), 'status' => $classify->project->get('stage')));
		break;

	case 'getRecords':
		$timeStart = microtime(true);
		$projectId = trim($projectId);
		$filter['projectId'] = $projectId;
		if(!$classify->project->projectExists($config['db']['name'],$projectId)) {
			print json_encode(array('success' => false, 'error' => array('code' => 110, 'msg' => $classify->getError(110))));
			break;
		}
		if(!$classify->project->loadByProjectId($projectId)) {
			$valid = false;
			$code = 101;
		}

		$filter['start'] = (trim($start) == '') ? 0 : trim($start);
		$filter['limit'] = (trim($limit) == '') ? 100 : trim($limit);
		$filter['field'] = trim($field);
		$filter['query'] = trim($query);
		$filter['searchType'] = in_array(trim($searchType),array('anymatch','startswith','endswith','exactmatch')) ? trim($searchType) : 'startswith';
		$filter['stage'] = $classify->project->get('stage');
		if($sort != '') {
			if ($filter['stage'] == "LOADED") {
				$sort = str_replace('_p','_o', $sort);			
			}
			$filter['order'] = array(array('field' => $sort, 'dir' => $dir));
		}

		if($valid) {
			$totalRecordCount = $classify->project->getTotalRecordCount($projectId);
			$records = $classify->project->getByTableFilter($filter);
		}
		$records = (is_null($records)) ? array() : $records;
		print json_encode(array('success' => true,'processTime' => (microtime(true) - $timeStart), 'recordTotal' => $classify->project->db->query_total(), 'totalRecordCount' => $totalRecordCount, 'records' => $records));
		break;
	case 'summary':
		$timeStart = microtime(true);
		$projectId = trim($projectId);
		$filter['projectId'] = $projectId;
		if(!$classify->project->loadByProjectId($projectId)) {
			$valid = false;
			$code = 101;
		}
		if($valid) {
			$summary = array(
				  'kingdom' => $classify->project->get('kingdom')
				, 'kingdom_variance' => $classify->project->get('kingdom_variance')
				, 'phylum' => $classify->project->get('phylum')
				, 'phylum_variance' => $classify->project->get('phylum_variance')
				, 'class' => $classify->project->get('class')
				, 'class_variance' => $classify->project->get('class_variance')
				, 'order' => $classify->project->get('order')
				, 'order_variance' => $classify->project->get('order_variance')
				, 'family' => $classify->project->get('family')
				, 'family_variance' => $classify->project->get('family_variance')
				, 'genus' => $classify->project->get('genus')
				, 'genus_variance' => $classify->project->get('genus_variance')
				, 'scientificName' => $classify->project->get('scientificName')
				, 'scientificName_variance' => $classify->project->get('scientificName_variance')
				);
				print json_encode(array('success' => true,'processTime' => (microtime(true) - $timeStart), 'summary' => array($summary)));
		} else {
			print json_encode(array('success' => false, 'error' => array('code' => $code, 'msg' => $classify->getError($code))));
		}
		break;

	case 'testTask':
		var_dump($classify->project->getTotalRecordCount(trim($projectId)));
		break;

	default:
		print 'No Command Given.';
		break;
}

?>